package com.liry.security.service.impl;

import com.liry.security.domain.entity.Role;
import com.liry.security.domain.entity.UserRole;
import com.liry.security.domain.entity.SysUser;
import com.liry.security.repository.RoleRepository;
import com.liry.security.repository.SysUserRepository;
import com.liry.security.repository.UserRoleRepository;
import com.liry.security.service.SysUserService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author ALI
 * @since 2023/5/29
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl implements SysUserService {

    private SysUserRepository sysUserRepository;
    private UserRoleRepository userRoleRepository;
    private RoleRepository roleRepository;
    @Override
    public SysUser getByUsername(String username) {
        SysUser user = sysUserRepository.getByUsername(username);
        if (user == null) {
            return null;
        }
        List<UserRole> roles = userRoleRepository.getByUserId(user.getId());
        if (roles.isEmpty()) {
            return user;
        }
        List<Integer> roleIds = roles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if (roleIds.isEmpty()) {
            return user;
        }
        user.setRoles(roleRepository.listByIds(roleIds).stream().map(Role::getCode).collect(Collectors.toList()));
        return user;
    }
}
